import time
import json
from datetime import datetime
from sp_api.api import Products
from sp_api.base import Marketplaces, Credentials
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.intereface_amazon.databasemodel import AmazonProduct, Base
from app.intereface_amazon.amazon_config import SP_API_CREDENTIALS, MARKETPLACE_CONFIG, DB_CONFIG

class AmazonProductDeleter:
    def __init__(self, marketplace_id='ATVPDKIKX0DER', db_url=None):
        """
        初始化亚马逊产品删除器
        
        参数:
            marketplace_id: 市场ID，默认为美国市场
            db_url: 数据库连接URL
        """
        self.marketplace_id = marketplace_id
        self.marketplace = Marketplaces.US  # 默认使用美国市场
        
        # 设置认证信息
        self.credentials = Credentials(
            refresh_token=SP_API_CREDENTIALS['refresh_token'],
            lwa_app_id=SP_API_CREDENTIALS['lwa_app_id'],
            lwa_client_secret=SP_API_CREDENTIALS['lwa_client_secret'],
            aws_access_key=SP_API_CREDENTIALS['aws_access_key'],
            aws_secret_key=SP_API_CREDENTIALS['aws_secret_key'],
            role_arn=SP_API_CREDENTIALS['role_arn']
        )
        
        # 初始化Products API
        self.products_api = Products(
            marketplace=self.marketplace,
            credentials=self.credentials
        )
        
        # 初始化数据库连接
        if db_url:
            self.engine = create_engine(db_url)
        else:
            self.engine = create_engine(DB_CONFIG['url'])
        Base.metadata.create_all(self.engine)
        self.Session = sessionmaker(bind=self.engine)
    
    def delete_products(self, sku_list, batch_size=5, update_db=True):
        """
        批量删除亚马逊产品
        
        参数:
            sku_list: SKU列表
            batch_size: 每批处理的SKU数量，默认为5
            update_db: 是否更新数据库，默认为True
        
        返回:
            删除结果列表
        """
        delete_results = []
        session = self.Session()
        
        try:
            for i in range(0, len(sku_list), batch_size):
                batch = sku_list[i:i+batch_size]
                
                try:
                    # 准备删除请求
                    delete_request = {
                        'skus': batch
                    }
                    
                    # 调用Products API删除产品
                    response = self.products_api.delete_product(
                        body=delete_request
                    )
                    
                    # 处理响应
                    if response.payload:
                        # 更新数据库
                        if update_db:
                            for sku in batch:
                                try:
                                    # 查找产品
                                    product = session.query(AmazonProduct).filter_by(sku=sku).first()
                                    
                                    if product:
                                        # 更新产品状态为已删除
                                        product.status = 'deleted'
                                        product.updated_at = datetime.now()
                                    
                                    delete_results.append({
                                        'sku': sku,
                                        'status': 'success'
                                    })
                                    
                                except Exception as e:
                                    delete_results.append({
                                        'sku': sku,
                                        'status': 'error',
                                        'message': str(e)
                                    })
                                    print(f"更新产品状态到数据库时出错: {e}")
                                    continue
                            
                            # 提交事务
                            session.commit()
                        else:
                            for sku in batch:
                                delete_results.append({
                                    'sku': sku,
                                    'status': 'success'
                                })
                    else:
                        delete_results.append({
                            'batch': i // batch_size + 1,
                            'status': 'error',
                            'message': 'No payload in response'
                        })
                    
                    # 添加延迟以避免API限制
                    time.sleep(2)
                    
                except Exception as e:
                    session.rollback()
                    delete_results.append({
                        'batch': i // batch_size + 1,
                        'status': 'error',
                        'message': str(e)
                    })
                    print(f"删除产品批次时出错: {e}")
                    continue
                
        finally:
            session.close()
        
        return delete_results
    
    def save_results_to_file(self, results, output_file='delete_results.json'):
        """
        将删除结果保存到JSON文件
        
        参数:
            results: 删除结果列表
            output_file: 输出文件名
        """
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(results, f, indent=4)
        
        print(f"删除结果已保存到 {output_file}")

# 使用示例
if __name__ == "__main__":
    # 数据库连接URL
    db_url = "mysql+pymysql://username:password@localhost:3306/database_name"
    
    # 创建删除器实例
    deleter = AmazonProductDeleter(db_url=db_url)
    
    # 示例SKU列表
    sku_list = ['TEST-SKU-001', 'TEST-SKU-002', 'TEST-SKU-003']
    
    # 删除产品
    delete_results = deleter.delete_products(sku_list)
    
    # 保存结果
    deleter.save_results_to_file(delete_results) 